package com.example.springbootdemo.serivce;

import com.example.springbootdemo.entity.User;
import com.example.springbootdemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @PersistenceContext
    EntityManager entityManager;

    @Autowired
    private UserRepository userRepository;

    @Override
    public Long count() {
        return userRepository.count();
    }

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public List<User> getUser(String queryName, int start, int limit) {
        List<User> list = entityManager.createQuery("from User where name like :name order by id")
        .setParameter("name", "%"+queryName+"%")
                .setFirstResult(start)
                .setMaxResults(limit)
                .getResultList();
        return list;
    }

    @Override
    public Long getUserCount(String queryName) {
        Object count = entityManager.createQuery("SELECT count(*) from User where name like :name")
                .setParameter("name", "%"+queryName+"%").getSingleResult();
        if(count==null) return 0L;
        return (Long)count;
    }
}
